import axios from 'axios'
import md5 from 'js-md5'
import store from '@/store/store'
import {
  Toast
} from 'vant'
import {
  getDataByKey
} from '@/utils/util'

let baseURL = ''

const signParam = function (_param, _requestTime) {
  var map = {};
  map["requestTime"] = _requestTime;
  map["secretKey"] = store.state.appKeyObj.secretKey;
  var keys = [];
  keys.push("requestTime");
  keys.push("secretKey");

  for (var key in _param) {
    if (_param[key] != undefined) {
      keys.push(key);
      map[key] = _param[key];
    }
  }
  keys.sort();
  var array = new Array();
  for (var i = 0; i < keys.length; i++) {
    array.push(keys[i]);
    array.push("=");
    array.push(map[keys[i]]);
  }
  var sb = array.join("") + "";
  var sign = md5(sb).toUpperCase();
  return sign;
}

const transGetParam = function (ajaxParam) {
  let userInfor = store.state.userInfo
  var sysP = {};
  var navP = ajaxParam;
  navP.userName = userInfor ? userInfor.accountName : "";
  navP.deviceId = store.state.appKeyObj.deviceId;
  sysP.requestTime = Date.parse(new Date());
  sysP.appKey = store.state.appKeyObj.appKey;
  sysP.sign = signParam(navP, sysP.requestTime);
  return {
    sysParams: JSON.stringify(sysP),
    params: JSON.stringify(navP)
  };
}

const transParam = function (ajaxParam) {
  let userInfor = store.state.userInfo
  var sysP = {};
  var navP = ajaxParam;
  navP.userName = userInfor ? userInfor.accountName : "";
  navP.deviceId = store.state.appKeyObj.deviceId;

  sysP.requestTime = Date.parse(new Date());
  sysP.appKey = store.state.appKeyObj.appKey;
  sysP.sign = signParam(navP, sysP.requestTime);
  return JSON.stringify({
    sysParams: sysP,
    params: navP
  });
}

// 设置 POST 请求头
axios.defaults.headers.post['Content-Type'] = 'application/json'

// 在向服务器发送前，修改请求数据(只能用在 'PUT', 'POST' 和 'PATCH' 这几个请求方法)
// axios.defaults.transformRequest = [(data) => { return JSON.stringify(data) }]

// 在传递给 then/catch 前，允许修改响应数据
// axios.defaults.transformResponse = [(data) => { return JSON.parse(data) }]

// 配置 CORS 跨域
// 表示跨域请求时是否需要使用凭证
axios.defaults.withCredentials = true
axios.defaults.dataType = 'json'

axios.defaults.crossDomain = true

axios.defaults.emulateJSON = true

// 设置超时
axios.defaults.timeout = 120000

// 拦截器的说明
// 1、interceptor必须在请求前设置才有效。
// 2、直接为axios全局对象创建interceptor， 会导致全局的axios发出的请求或接收的响应都会被拦截到， 所以应该使用axios.create() 来创建单独的axios实例。
// 设置地址

// 创建axios实例
const instance = axios.create()

// 拼装url
function getUrl(url, params) {
  let i = 0
  if (!params) {
    params = {}
  }
  if (url.indexOf('/') !== 0) {
    url = '/' + url
  }
  if (url.indexOf('?') < 0) {
    url += '?'
  } else {
    url += '&'
  }
  for (const item in params) {
    i += 1
    if (typeof params[item] !== 'function') {
      url +=
        encodeURIComponent(item) +
        '=' +
        encodeURIComponent(params[item]) +
        (i !== Object.getOwnPropertyNames(params).length ? '&' : '')
    }
  }
  return url
}
// Add a request interceptor
instance.interceptors.request.use(
  config => {
    return config
  },
  error => {
    // Do something with request error
    console.error(error)
    Promise.reject(error)
  }
)

// Add a response interceptor
instance.interceptors.response.use(
  function (response) {
    return response.data
  },
  function (error) {
    // 过期
    if (error.response.status === 401) {

    }
    return Promise.reject(error)
  }
)

/**
 *  暴露fetch方法，调用后台接口
 * @param url
 * @param params
 * @returns {Promise}
 */
const get = (url, params, secret = true) => {

  if (!baseURL) {
    baseURL = location.href.indexOf('http') == 0 ? '/app/' : getDataByKey('contextPath') + 'app/'
  }

  let IS_OFFLINE_MODULE = store.state.isOffline
  if (IS_OFFLINE_MODULE) {
    let key = "offlineData-app/" + url + JSON.stringify(params);
    let data = null;
    if (getDataByKey(key)) {
      data = JSON.parse(getDataByKey(key));
    }
    console.log("key:" + key);
    if (!data) {
      console.log("data数据未获取到，" + key);
      data = {
        "data": { "status": 303, "info": "当前任务不包含该点位" },
        "info": "操作成功",
        "status": 200,
        "total": 0
      }
    }
    return new Promise((resolve) => {
      resolve(data)
    })
  }
  if (secret) {
    params = transGetParam(params)
  }
  return new Promise((resolve, reject) => {
    instance
      .get(getUrl(url, params), {
        baseURL
      })
      .then(
        response => {
          if (!response || response.status !== 200) {
            console.warn(
              url + '：' + (response ? response.info : ''),
              'error'
            )
            // Toast(response ? response.info : '')
            reject(response)
          } else {
            resolve(response)
          }
        },
        err => {
          // reject(err)
        }
      )
      .catch(error => {
        reject(error)
      })
  })
}
const post = (url, data, secret = true) => {
  if (!baseURL) {
    baseURL = location.href.indexOf('http') == 0 ? '/app/' : getDataByKey('contextPath') + 'app/'
  }
  if (secret) {
    data = transParam(data)
  }
  return instance.post(url, data, {
    baseURL
  })
}

const getJSON = axios.create({
  timeout: 20000
})

export default {
  get,
  post,
  instance,
  getJSON
}
